#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <e_file.h>
#include <string.h>

#define BUFFSIZE 128
#define FILENAME  "/tmp/out"

int mydaemon (void);
int main (void)
{
	FILE *fp;
	time_t tm;
	struct tm *tmp;
	char buf[BUFFSIZE] = {};
	// 创建守护进程 
	if (-1 == mydaemon()) {
		exit (-1);
	}
	// 打开文件，获取系统时间并写入
	fp = fopen (FILENAME, "w");
	if (NULL == fp)
	{
		perror ("fopen()");
		return -1;
	}
	while (1) {
		time (&tm);
		tmp = localtime (&tm);
		if (NULL == tmp) {
			perror ("localtime()");
			exit (1);
		}
		memset (buf, 0, BUFFSIZE);
		strftime (buf, BUFFSIZE, "%Y/%m/%d %H:%M:%S\n", tmp);
		fputs (buf, fp);
		fflush (NULL);
		sleep (1);
	}
	fclose (fp);
	return 0;
}

int mydaemon (void)
{
	pid_t pid;
	pid = fork();
	if (-1 == pid) {
		perror ("fork()");
		exit (-1);
	}
	//直接让父进程终止
	if (pid > 0) {
		exit (0);
	}
	//子进程 
	if (-1 == setsid()) {
		perror ("setsid()");
		return -1;
	}
	
	//pid==PGID==SID 脱离终端的控制, 守护进程的必要条件 
	umask (0);
	chdir ("/");
	int fd = open ("/dev/null", O_RDWR);
	if (-1 == fd) {
		perror ("open()");
		return -1;
	}
	dup2 (0, fd);
	dup2 (1, fd);
	dup2 (2, fd);
	if (fd > 2 ) {
		close (fd);
	}
	return 0;
}














